#include "editorfactory.h"
#include "cppeditor.h"
#include "pythoneditor.h"
#include <QDebug>

BaseEditor* EditorFactory::createEditor(LanguageType type, QWidget *parent)
{
    switch (type) {
        case LanguageType::CPP:
            return new CppEditor(parent);
        case LanguageType::PYTHON:
            return new PythonEditor(parent);
        case LanguageType::UNKNOWN:
        default:
            qWarning() << "Unsupported language type:" << static_cast<int>(type);
            return nullptr;
    }
}

BaseEditor* EditorFactory::createEditorByExtension(const QString &extension, QWidget *parent)
{
    LanguageType type = inferLanguageFromExtension(extension);
    return createEditor(type, parent);
}

QList<LanguageType> EditorFactory::getSupportedLanguages()
{
    return { LanguageType::CPP, LanguageType::PYTHON };
}

QString EditorFactory::getLanguageDisplayName(LanguageType type)
{
    switch (type) {
        case LanguageType::CPP:
            return "C++";
        case LanguageType::PYTHON:
            return "Python";
        case LanguageType::UNKNOWN:
        default:
            return "Unknown";
    }
}

QStringList EditorFactory::getLanguageExtensions(LanguageType type)
{
    switch (type) {
        case LanguageType::CPP:
            return { "cpp", "cc", "cxx", "c++", "c", "h", "hpp", "hxx", "h++", "hh" };
        case LanguageType::PYTHON:
            return { "py", "pyw", "pyx", "pyi" };
        case LanguageType::UNKNOWN:
        default:
            return {};
    }
}

LanguageType EditorFactory::inferLanguageFromExtension(const QString &extension)
{
    QString lowerExt = extension.toLower();

    // 移除点号（如果有的话）
    if (lowerExt.startsWith('.')) {
        lowerExt = lowerExt.mid(1);
    }

    // C++扩展名
    QStringList cppExtensions = getLanguageExtensions(LanguageType::CPP);
    if (cppExtensions.contains(lowerExt)) {
        return LanguageType::CPP;
    }

    // Python扩展名
    QStringList pythonExtensions = getLanguageExtensions(LanguageType::PYTHON);
    if (pythonExtensions.contains(lowerExt)) {
        return LanguageType::PYTHON;
    }

    return LanguageType::UNKNOWN;
}
